package com.weyoung.app.consumer;

import com.rabbitmq.client.Channel;
import com.weyoung.app.dto.req.GraNodeMessage;
import com.weyoung.common.config.RabbitMQConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import static com.weyoung.common.utils.RedisConstants.GRAVE_VISITING_NODE_KEY;
import static com.weyoung.common.utils.RedisConstants.GRAVE_VISITING_NODE_LIST_KEY;

@Slf4j
@Component
@RequiredArgsConstructor
public class GraveNodeConsumer {

    private final StringRedisTemplate stringRedisTemplate;

    @RabbitListener(queues = RabbitMQConfig.GRAVE_QUEUE_NAME)
    public void consume(GraNodeMessage message,
                        Channel channel,
                        @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        log.info("[墓地节点消息队列] -》 收到消息：{}", message);
        try {
            // 删除缓存
            // 1、删除家族墓地节点列表缓存
            stringRedisTemplate.delete(GRAVE_VISITING_NODE_LIST_KEY + message.getFamilyId());
            // 2、删除墓地节点缓存
            stringRedisTemplate.delete(GRAVE_VISITING_NODE_KEY + message.getNodeId());
            // 立刻消费
            channel.basicAck(deliveryTag, false);
        }catch (Exception e){
            log.error("消费消息失败：{}", e.getMessage());
            consume(message, channel, deliveryTag);
        }

    }
}
